import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { Upload, message, type GetProp, type UploadProps } from "antd";
import { useEffect, useState } from "react";
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

interface UploadImgProps {

    defaultImgUrl?: string,
    uploadHandle: (url: string) => void;
}
function UploadImg({ uploadHandle, defaultImgUrl }: UploadImgProps) {

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string | undefined>(defaultImgUrl);


    const headers = { 'Authorization': localStorage.getItem('token')! }

    useEffect(() => {
        if (defaultImgUrl) {
            setImageUrl(defaultImgUrl);
        }
    }, [defaultImgUrl]);

    const beforeUpload = (file: FileType) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };


    const handleChange: UploadProps['onChange'] = (info) => {
        console.log("222222222");

        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {

            console.log("1111111", info.file.response.data);
            setLoading(false);

            setImageUrl(info.file.response.data);
            uploadHandle(info.file.response.data);


        }
    };


    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            {/* <div style={{ marginTop: 8 }}>Upload</div> */}
        </button>
    );

    return (
        <>
            <Upload
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                headers={headers}
                action={import.meta.env.VITE_API_BASE_URL + '/upload/add'}
                beforeUpload={beforeUpload}
                onChange={handleChange}
            >
                {imageUrl ? <img src={import.meta.env.VITE_API_BASE_IGM + imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}

            </Upload>
        </>
    )

}
export default UploadImg;